<script setup lang='ts'>
  import { reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { User, Lock } from '@element-plus/icons-vue'
  import type { LoginPO } from '@/types/auth.d'
  import { login } from '@/http/api/auth'
  import { useRouter } from 'vue-router'

  import store from '@/stores'

  import { initRouter } from '@/router'

  const router = useRouter()

  const loginFormRef = ref<FormInstance>()
  const loginForm = reactive<LoginPO>({
    username: '',
    password: ''
  })

  const rules = reactive<FormRules<LoginPO>>({
    username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  })

  const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log('submit!')
        login(loginForm).then((res: any) => {
        // console.log(res)
        if(res.msg){
          ElMessage({
            showClose: true,
            message: res.msg,
            type: 'error',
            duration: 10000
          })
        }else{
          //console.log(res.data)
          let menuList = res.data.menuList
          store.router.setMenuList(menuList)
          initRouter(menuList)
          router.push({ path: '/' })
        }
      })
    } else {
      // console.log('error submit!', fields)
    }
  })
}

</script>
<template>
  <div class="viewport">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <div class="div-form">
          <h1>八卦程序</h1>
          <h2>后台管理系统</h2>
          <el-form ref="loginFormRef" :model="loginForm" :rules="rules">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" :prefix-icon="User" placeholder="账号" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" :prefix-icon="Lock" type="password" placeholder="密码" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="eb-login" @click="submitForm(loginFormRef)">登 录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<style scoped lang='scss'>
  .viewport {
    width: 100vw;
    height: 100vh;
    background: url('@/assets/img/background.jpg') no-repeat;
    background-size: cover;
    .div-form {
      position: relative;
      top: 30vh;
      width: 80%;
      background: url('@/assets/img/login-form.png') no-repeat;
      background-size: cover;
      padding: 40px;
      h1 {
        color: white;
        font-size: 40px;
      }
      h2 {
        color: white;
        font-size: 20px;
        margin: 20px 0;
      }
      .eb-login {
        width: 100%;
      }
    }
  }
</style>